package com.sdyeda.readiot.tools;

import java.util.Calendar;

import org.springframework.stereotype.Service;

@Service
public class SendBuff {
	
	private static final int size = 21;
	private byte[] buff =new byte[size];
	//00 01 02  03   04  05  06 07 08 09 10 11 12 13 14 15 16 17 18 19 20
	//头（2）动作 数据长度 保留 |传感器编号，8字节         |操作时间6字节       |校验和                        
	//AA 75 10  高字在前  00 |                       |                  |
	
	
	public SendBuff() {
		Init();
	}
	
	public void Init() {
		clearBuff();
		initBuff();
		setTime();
	}	
	
	public byte[] getBuff() {
		return buff;
	}
	
	public int getSize() {
		return size;
	}

	void clearBuff() {
		for (int i = 0; i < size; i++) buff[i] = 0;
	}
	
	void initBuff() {
		buff[0] = (byte) 0xAA;
		buff[1] = (byte) 0x75;
		buff[2] = (byte) 0x10; // 读取
		buff[4] = (byte) 0x0E; // 数据长度，14字节
	}
	
	void setCheck() {
		byte check = 0;
		//System.out.println(buff.length);
		for (int i=0;i<buff.length-1;i++) {
			check ^= buff[i];
		}
		buff[size - 1] = check;
	}
	
	public void setCommand(byte command) {
		buff[2]=command;
		setCheck();
	}

	public void setIdonly(String id) {
		clearBuff();
		initBuff();
		System.arraycopy(HexTools.hexStringToByteArray(id), 0, buff, 6, 8);
		setCheck();
	}
	public void setId(String id) {
		Init();
		//System.out.println(id); 
		System.arraycopy(HexTools.hexStringToByteArray(id), 0, buff, 6, 8);
		setCheck();
	}
	public void setRainId(String id) {

		setId(id);
		//  读取指令 
		//18H 读取雨量计全部记录
		//1AH 读取当日雨量数据
		//1BH 读取指定日期雨量数据
		//10H 传统读取

		Calendar date = Calendar.getInstance();
		
		if(date.get(Calendar.HOUR_OF_DAY) ==0) {	//夜里0点
			buff[2] = (byte) 0x1B; // 读取昨天数据
			setRainTime();
		}
		else {
			buff[2] = (byte) 0x1A; // 读取今天某天数据
		}
		setCheck();
	}
	
	
	void setTime() {
		System.arraycopy(HexTools.getBytesTimeBCD(), 0, buff, 14, 6);	//年月日
	}
	
	void setRainTime() {
		System.arraycopy(HexTools.getBytesRainTimeBCD(), 0, buff, 14, 6);
	}

	
	public String toString() {
		return toHexString();
	}
		
	public String toHexString() {
		return HexTools.bytesToHex(buff);
	}
}
